﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using MySql.Data.MySqlClient;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.PrepayOrder;
using User.Api.Helpers;

namespace User.Api.Controllers
{
    public class PrepayOrderController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(PrepayOrderController));
        private GdsfybjyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有住院预缴金订单，只显示成功的订单
        /// </summary>
        /// <param name="type">current - 60内订单 history - 历史订单</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderList")]
        public GetOrderListResponse GetOrderList(string type = "current")
        {
            var azUser = AzUser.GetInApi(Request);
            List<GetOrderListResponse.Order> orders;

            if (type == "current")
            {
                //orders =
                //    _ctx.InpatientPrepayOrders.Where(x => x.OpenId == azUser.OpenId).IsStatus(PrepayOrderExtensions.OrderStatus.缴费成功)
                //        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) <= 60)
                //        .OrderByDescending(x => x.CreateTime).ToList();
                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    MySqlParameter[] para =
                    {
                    new MySqlParameter("@OrderStatus", PrepayOrderExtensions.OrderStatus.缴费成功.ToInt32()),
                    new MySqlParameter("@Today", DateTime.Today)
                };
                    orders = ctx.Database.SqlQuery<GetOrderListResponse.Order>(
                        "select Id as OrderId,CardNo,CardName,OrderNo,date_format(CreateTime, '%Y-%m-%d %H:%i:%s') as CreateDt,PrepayMoney from InpatientPrepayOrder where OrderStatus = @OrderStatus and datediff(@Today,CreateTime)<=15    ",
                        para).ToList();
                }
            }
            else
            {
                //orders =
                //    _ctx.InpatientPrepayOrders.Where(x => x.OpenId == azUser.OpenId).IsStatus(PrepayOrderExtensions.OrderStatus.缴费成功)
                //        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) > 60)
                //        .OrderByDescending(x => x.CreateTime).ToList();
                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    MySqlParameter[] para =
                    {
                    new MySqlParameter("@OrderStatus", PrepayOrderExtensions.OrderStatus.缴费成功.ToInt32()),
                    new MySqlParameter("@Today", DateTime.Today)
                };
                    orders = ctx.Database.SqlQuery<GetOrderListResponse.Order>(
                        "select Id as OrderId,CardNo,CardName,OrderNo,date_format(CreateTime, '%Y-%m-%d %H:%i:%s') as CreateDt,PrepayMoney from InpatientPrepayOrder where OrderStatus = @OrderStatus and datediff(@Today,CreateTime)>15  ",
                        para).ToList();
                }
            }

            return new GetOrderListResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Orders = orders
            };
        }

        /// <summary>
        /// 获取住院预缴金订单详情
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderDetail")]
        public GetOrderDetailResponse GetOrderDetail(int orderId)
        {
            var azUser = AzUser.GetInApi(Request);
            var order = _ctx.InpatientPrepayOrders.IsStatus(PrepayOrderExtensions.OrderStatus.缴费成功)
                .FirstOrDefault(x => x.OpenId == azUser.OpenId && x.Id == orderId);
            if (order == null)
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "订单不存在"
                };
            }
            
            return new GetOrderDetailResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                OrderId = order.Id,
                OrderNo = order.OrderNo,
                CardNo = order.CardNo,
                CardName = order.CardName,
                CreateDt = order.CreateTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm"),
                PrepayMoney = order.PrepayMoney.GetValueOrDefault().ToString("F2")
            };
        }

        /// <summary>
        /// 获取住院预缴金订单详情
        /// </summary>
        /// <param name="orderNo">订单本地单号</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderDetailByNo")]
        public GetOrderDetailResponse GetOrderDetailByNo(string orderNo)
        {
            var azUser = AzUser.GetInApi(Request);
            if (string.IsNullOrEmpty(orderNo) || orderNo.Length < 2)
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "订单不存在"
                };

            }
            string dbOrderNo = orderNo.Substring(2);

            var order = _ctx.InpatientPrepayOrders
                .FirstOrDefault(x => x.OpenId == azUser.OpenId && x.OrderNo == dbOrderNo);
            if (order == null)
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "订单不存在"
                };
            }

            return new GetOrderDetailResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                OrderId = order.Id,
                OrderNo = order.OrderNo,
                CardNo = order.CardNo,
                CardName = order.CardName,
                CreateDt = order.CreateTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm"),
                PrepayMoney = order.PrepayMoney.GetValueOrDefault().ToString("F2")
            };
        }
    }
}
